package com.fyy.netty.chapter03.c1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @Author fyy
 * @Description LTC解码器
 * @Date 2021/5/10 15:30
 */
public class LengthFieldDecoderTest {

    public static void main(String[] args) {

        EmbeddedChannel channel = new EmbeddedChannel(
                new LengthFieldBasedFrameDecoder(1024,0,4,1,4),
                new LoggingHandler(LogLevel.DEBUG)
        );

        //4个字节的内容长度，实际长度
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        send(buf,"hello, world");
        send(buf,"Hi");
        channel.writeInbound(buf);

    }

    private static void send(ByteBuf buf,String content){
        byte[] bytes = content.getBytes(); //实际内容
        int len = bytes.length; //实际内容长度
        buf.writeInt(len); //写入内容长度
        buf.writeByte(1); //写入任意数据
        buf.writeBytes(bytes); //写入实际内容
    }

}
